<template>
  <div>
    <h1>商品管理</h1>
    <!-- 查询 -->
    <div>
      <el-form :inline="true" :model="searData" class="demo-form-inline">
        <el-form-item label="关键字">
          <el-input
            v-model="searData.keyWord"
            placeholder="品牌/名称/ID/SPU"
            clearable
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="getProdList()">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-button type="success" @click="addProd()">添加</el-button>
    <el-button type="danger" @click="deleteBatch()">批量删除</el-button>
    <!-- 列表 -->
    <el-table
      :data="tableData"
      stripe
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="prodId" label="ID" />
      <el-table-column prop="prodSpu" label="SPU" />
      <el-table-column prop="kindName" label="种类" />
      <el-table-column prop="typeName" label="分类" />
      <el-table-column prop="prodName" label="名称" />
      <el-table-column prop="brandName" label="品牌" />
      <el-table-column prop="unitName" label="单位" />
      <el-table-column prop="tagName" label="标签" />
      <el-table-column prop="prodStatus" label="状态">
        <template #default="scope">
          <span v-if="scope.row.prodStatus == 0">草稿</span>
          <span v-if="scope.row.prodStatus == 1">待审核</span>
          <span v-if="scope.row.prodStatus == 2">已上线</span>
          <span v-if="scope.row.prodStatus == 3">已下线</span>
          <span v-if="scope.row.prodStatus == 4">缺货</span>
        </template>
      </el-table-column>
      <el-table-column prop="appr" label="供应商" />
      <el-table-column prop="prodImage" label="封面">
        <template #default="scope">
          <el-image
            style="width: 100px; height: 100px"
            :src="scope.row.prodImage"
            :fit="fit"
          />
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" />
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="success" @click="onProd(scope.row)" size="small"
            >商品</el-button
          >
          <el-button type="success" @click="onProdFu(scope.row)" size="small"
            >商品附件</el-button
          >
          <el-button type="danger" @click="deleteProd(scope.row)" size="small"
            >删除</el-button
          >
          <el-button type="danger" @click="onBuyPro(scope.row)" size="small"
            >购买</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div>
      <div class="demo-pagination-block">
        <el-pagination
          v-model:current-page="searData.pageNum"
          v-model:page-size="searData.pageSize"
          :page-sizes="[2, 3, 4, 5]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <!-- 新增弹框 -->
    <div>
      <el-dialog v-model="dialogFormVisible" title="商品添加" width="500">
        <el-form :model="form" ref="ruleFormRef" :rules="rules">
          <el-form-item
            label="商品类型"
            :label-width="formLabelWidth"
            prop="prodKind"
          >
            <el-radio-group v-model="form.prodKind">
              <el-radio
                v-for="item in ProdKindList"
                :value="item.dictValue"
                :key="item.dictId"
                >{{ item.dictName }}</el-radio
              >
            </el-radio-group>
          </el-form-item>

          <el-form-item
            label="商品分类"
            :label-width="formLabelWidth"
            prop="prodType"
          >
            <el-tree-select
              v-model="form.prodType"
              :data="SelectTypeTree"
              :render-after-expand="false"
              style="width: 240px"
            />
          </el-form-item>

          <el-form-item
            label="商品名称"
            :label-width="formLabelWidth"
            prop="prodName"
          >
            <el-input v-model="form.prodName" autocomplete="off" />
          </el-form-item>
          <el-form-item
            label="SPU"
            :label-width="formLabelWidth"
            prop="prodSpu"
          >
            <el-input v-model="form.prodSpu" autocomplete="off" />
          </el-form-item>
          <el-form-item
            label="商品品牌"
            :label-width="formLabelWidth"
            prop="brandId"
          >
            <el-select v-model="form.brandId" placeholder="商品品牌">
              <el-option
                v-for="item in BrandList"
                :label="item.brandName"
                :value="item.brandId"
              />
            </el-select>
          </el-form-item>

          <el-form-item
            label="商品单位"
            :label-width="formLabelWidth"
            prop="unitId"
          >
            <el-select v-model="form.unitId" placeholder="商品单位">
              <el-option
                v-for="item in unitList"
                :key="item.dictId"
                :label="item.dictName"
                :value="item.dictValue"
              />
            </el-select>
          </el-form-item>

          <el-form-item
            label="商品标签"
            :label-width="formLabelWidth"
            prop="tagId"
          >
            <el-select v-model="form.tagId" placeholder="商品标签">
              <el-option
                v-for="item in tagList"
                :label="item.dictName"
                :value="item.dictValue"
                :key="item.dictId"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="供应商"
            :label-width="formLabelWidth"
            prop="appr"
          >
            <el-input v-model="form.appr" autocomplete="off" />
          </el-form-item>
          <el-form-item
            label="商品缩略图"
            :label-width="formLabelWidth"
            prop="prodImage"
          >
            <el-upload
              class="avatar-uploader"
              action="http://localhost:10010/user/type/uploadTypeImage"
              :headers="headers"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="submitForm(ruleFormRef)">
              确认
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
    <!-- 商品弹框 -->
    <div>
      <el-dialog v-model="dialogFormVisible1" title="商品附件" width="500">
        <el-form :model="formAtta">
          <el-form-item label="商品轮播图" :label-width="formLabelWidth">
            <el-upload
              v-model:file-list="fileList"
              action="http://localhost:10010/user/type/uploadTypeImage"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :headers="headers"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>

            <el-dialog v-model="dialogVisible">
              <img w-full :src="dialogImageUrl" alt="Preview Image" />
            </el-dialog>
          </el-form-item>

          <el-form-item label="商品视频" :label-width="formLabelWidth">
            <el-upload
              v-model:file-list="vedioList"
              class="upload-demo"
              action="http://localhost:10010/user/type/uploadTypeImage"
              multiple
              :on-preview="handlePreview"
              :on-remove="handleViewRemove"
              :before-remove="beforeRemove"
              :limit="1"
              :on-exceed="handleExceed"
              :headers="headers"
            >
              <el-button type="primary">上传视频</el-button>
              <template #tip>
                <div class="el-upload__tip">
                  作用于商品详情页顶部轮插的视频介绍,最大限制20MB.
                </div>
              </template>
            </el-upload>
          </el-form-item>
          <el-form-item label="上架时间" :label-width="formLabelWidth">
            <el-radio-group v-model="formAtta.upFlag">
              <el-radio :value="0">立即上架</el-radio>
              <el-radio :value="1">定时下架</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item
            label=""
            :label-width="formLabelWidth"
            v-if="formAtta.upFlag == '1'"
          >
            <span class="demonstration"></span>
            <el-date-picker
              v-model="formAtta.upTime"
              type="datetime"
              placeholder="请选择上架时间"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>

          <el-form-item label="定时下架" :label-width="formLabelWidth">
            <el-switch
              v-model="formAtta.downFlag"
              :active-value="0"
              :inactive-value="1"
            />
          </el-form-item>

          <el-form-item
            label=""
            :label-width="formLabelWidth"
            v-if="formAtta.downFlag == '0'"
          >
            <span class="demonstration"></span>
            <el-date-picker
              v-model="formAtta.downTime"
              type="datetime"
              placeholder="请选择下架时间"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">放弃</el-button>
            <el-button type="primary" @click="onAddProAtta()"> 添加 </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import {
  getProdListService,
  getDictListService,
  getSelectTypeTreeService,
  getBrandListService,
  addProdService,
  addProdAttaService,
  deleteBatchProdService,
  deleteProdService,
} from "../api/api";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";
const router = useRouter();
import { Plus } from "@element-plus/icons-vue";
import type { UploadProps, UploadUserFile } from "element-plus";

//购买
const onBuyPro = (row: any) => {
  console.log("onBuyPro", row);
};

//批量删除
const multipleSelection = ref<any[]>([]);
//多选后的商品列表
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val;
};

const deleteBatch = () => {
  let ids = [];
  if (multipleSelection.value.length == 0) {
    ElMessage.error("请选择要删除的商品");
  }
  multipleSelection.value.forEach((item) => {
    ids.push(item.prodId);
  });
  console.log("ids", ids);

  ElMessageBox.confirm("删除后不可恢复,是否删除?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      deleteBatchProdService(ids).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("删除成功");
          getProdList();
        } else {
          ElMessage.error("删除失败");
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消删除",
      });
    });
};

//单删
const deleteProd = (row: any) => {
  ElMessageBox.confirm("删除后不可恢复,是否删除?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      deleteProdService(row.prodId).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("删除成功");
          getProdList();
        } else {
          ElMessage.error("删除失败");
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消删除",
      });
    });
};

const dialogFormVisible = ref(false);
const dialogFormVisible1 = ref(false);
const formLabelWidth = "140px";
const ruleFormRef = ref<FormInstance>();
const checkprodImage = (rule: any, value: any, callback: any) => {
  if (imageUrl.value == null || imageUrl.value == "") {
    return callback(new Error("请上传图片"));
  } else {
    return callback();
  }
};
const rules = reactive<FormRules>({
  prodKind: [{ required: true, message: "商品类型不能为空", trigger: "blur" }],
  prodType: [{ required: true, message: "商品分类不能为空", trigger: "blur" }],
  prodName: [{ required: true, message: "商品名称不能为空", trigger: "blur" }],
  prodSpu: [{ required: true, message: "SPU不能为空", trigger: "blur" }],
  brandId: [{ required: true, message: "商品品牌不能为空", trigger: "blur" }],
  unitId: [{ required: true, message: "商品单位不能为空", trigger: "blur" }],
  tagId: [{ required: true, message: "商品标签不能为空", trigger: "blur" }],
  appr: [{ required: true, message: "供应商不能为空", trigger: "blur" }],
  prodImage: [{ required: true, validator: checkprodImage, trigger: "blur" }],
});
const form = ref({
  prodId: null,
  prodSpu: null,
  prodKind: null,
  prodType: null,
  prodName: null,
  brandId: null,
  createBy: null,
  createTime: null,
  updateBy: null,
  updateTime: null,
  unitId: null,
  tagId: null,
  appr: null,
  prodImage: null,
  prodStatus: null,
});
// 商品附件相关
const formAtta = ref({
  upFlag: null,
  downFlag: null,
  upTime: null,
  downTime: "",
  attaImages: "",
  attaVideo: "",
  prodId: null,
});
const fileList = ref<UploadUserFile[]>([]);
const vedioList = ref<UploadUserFile[]>([]);
const dialogImageUrl = ref("");
const dialogVisible = ref(false);

const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
};

const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};
const handleViewRemove: UploadProps["onRemove"] = (file, uploadFiles) => {
  console.log(file, uploadFiles);
};

const handlePreview: UploadProps["onPreview"] = (uploadFile) => {
  console.log(uploadFile);
};

const handleExceed: UploadProps["onExceed"] = (files, uploadFiles) => {
  ElMessage.warning(
    `The limit is 3, you selected ${files.length} files this time, add up to ${
      files.length + uploadFiles.length
    } totally`
  );
};

const beforeRemove: UploadProps["beforeRemove"] = (uploadFile, uploadFiles) => {
  return ElMessageBox.confirm(
    `Cancel the transfer of ${uploadFile.name} ?`
  ).then(
    () => true,
    () => false
  );
};

//商品附件弹框
const onProdFu = (row: any) => {
  //清空商品附件的值
  formAtta.value = {
    upFlag: null,
    downFlag: null,
    upTime: null,
    downTime: "",
    attaImages: "",
    attaVideo: "",
    prodId: null,
  };
  //清空轮播图
  fileList.value = [];
  //清空视频
  vedioList.value = [];
  //商品Id赋值
  formAtta.value.prodId = row.prodId;
  dialogFormVisible1.value = true;
};
//添加商品附件
const onAddProAtta = () => {
  //获取轮播图地址
  let attaImagesList: any = [];
  fileList.value.forEach((item) => {
    console.log("item", item, item.response.data);
    attaImagesList.push(item.response.data);
  });
  formAtta.value.attaImages = JSON.stringify(attaImagesList);
  //获取视频地址
  if (vedioList.value.length <= 0) {
    ElMessage.error("请上传视频");
    return;
  }
  formAtta.value.attaVideo = vedioList.value[0].response.data;
  console.log("formAtta.value", formAtta.value);
  addProdAttaService(formAtta.value).then((res) => {
    if (res.data.code == 200) {
      dialogFormVisible1.value = false;
      ElMessage.success("添加成功");
      getProdList();
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};

//添加商品弹框
const addProd = () => {
  dialogFormVisible.value = true;
};

const ProdKindList = ref([]);
const SelectTypeTree = ref([]);
const unitList = ref([]);
const tagList = ref([]);
const BrandList = ref([]);
const imageUrl = ref("");
const headers = ref({
  token: sessionStorage.getItem("token"),
});
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  //   imageUrl.value = URL.createObjectURL(uploadFile.raw!)
  imageUrl.value = response.data;
};

const tableData = ref([]);
const searData = ref({
  pageNum: 1,
  pageSize: 2,
  keyWord: null,
});
const total = ref(0);
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  searData.value.pageSize = val;
  getProdList();
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  searData.value.pageNum = val;
  getProdList();
};
const getProdList = () => {
  getProdListService(searData.value).then((res) => {
    if (res.data.code == 200) {
      tableData.value = res.data.data.records;
      total.value = res.data.data.total;
    }
  });
};

//添加
const onSubmitAddProd = () => {
  form.value.prodImage = imageUrl.value;
  addProdService(form.value).then((res) => {
    if (res.data.code == 200) {
      dialogFormVisible.value = false;
      ElMessage.success("添加成功");
      getProdList();
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
      onSubmitAddProd();
    } else {
      console.log("error submit!", fields);
    }
  });
};

onMounted(() => {
  getProdList();
  getDictListService(1).then((res) => {
    if (res.data.code == 200) {
      ProdKindList.value = res.data.data;
    }
  });
  getDictListService(2).then((res) => {
    if (res.data.code == 200) {
      unitList.value = res.data.data;
    }
  });
  getDictListService(3).then((res) => {
    if (res.data.code == 200) {
      tagList.value = res.data.data;
    }
  });

  getSelectTypeTreeService().then((res) => {
    if (res.data.code == 200) {
      SelectTypeTree.value = res.data.data;
    }
  });

  getBrandListService({ pageNum: 1, pageSize: 999 }).then((res) => {
    if (res.data.code == 200) {
      BrandList.value = res.data.data.records;
    }
  });
});
</script>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
